import Request from '@/utils/luch-request/index.js'
import Constant from './constant.js'

const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('token')
	} catch (e) {
		//TODO handle the exception
	}
	// token = '8e98e82072995c8b8f8e9ca3885bf7bb-4-1594084619165';
	// token = '333';
	console.log("token:" + token);
	return token
}

const http = new Request()

//https://e.dev.tuo51.com/
//http://192.168.3.146:8080/
//https://e.tuo51.com/
//https://e.dotflat.cn/
http.setConfig((config) => { /* config 为默认全局配置*/
	config.baseUrl = 'https://pe.jz1x.com/'; /* 根域名 */ //
	return config
})

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
	config.header = {
		...config.header,
		ticket: getTokenStorage()
	}
	return config
})

http.interceptor.response((response) => { /* 对响应成功做点什么 （statusCode === 200），必须return response*/
	if (response.statusCode !== 200) { // 服务端返回的状态码不等于200，则reject()
		return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
	}
	if (response.data.code === '000001' || response.data.code === '000011') {
		console.log(response.data)
		try {
			uni.setStorageSync('token', '');
		} catch (e) {}
		
		uni.switchTab({
			url: '/pages/index/index'
		});
		uni.$emit('event_ticket_refresh');
		return Promise.reject(response);
	}

	return response.data
}, (response) => { /*  对响应错误做点什么 （statusCode !== 200），必须return response*/
	console.log(response)
	return response
})

export {
	http,
}
